<?php
/**
 * Created by PhpStorm.
 * User: Steven
 * Date: 2017/6/28
 */

namespace app\pay\controller;


use app\classes\model\ClassModel;
use app\financial\model\OrderModel;
use cmf\controller\UserBaseController;
use think\Db;

class AlipayController extends UserBaseController
{
    public function _initialize()
    {
        parent::_initialize();
        //载入支付
        import('pay.alipay.Corefunction', EXTEND_PATH);
        import('pay.alipay.Md5function', EXTEND_PATH);
        import('pay.alipay.Notify', EXTEND_PATH);
        import('pay.alipay.Submit', EXTEND_PATH);
    }

    /**
     *支付请求
     */
    public function doAlipay()
    {
        $param = $this->request->param();
        if(!isset($param['order_id']) || empty($param['order_id'])){
            $this->error('订单编号不能为空','order/FrontOrder/index');
        }
        if(!isset($_SESSION['student_id']) || empty($_SESSION['student_id'])){
            //跳转到订单页
            $this->error('参数错误','order/FrontOrder/index');
        }

        $student_id = $_SESSION['student_id'];
        $order_id = base64_decode($param['order_id']);

        $where = [
            'o.order_id' => ['=', $order_id],
            'o.student_id' => ['=', $student_id],
        ];
        //获取订单
        $order_mdl = new OrderModel();
        $order = $order_mdl->getOrderByField($where);
        if(count($order) <= 0){
            //没有该订单
            $this->error('该订单不存在','order/FrontOrder/index');
            return false;
        }

        if($order['cancel_time'] < time()){
            //订单已过期，修改订单状态,同时释放座位，优惠返回等相关操作
            $update_data = [
                'id' => $order['id'],
                'order_status' => 3,//已取消
                'update_time' => time(),
            ];
            //修改订单
            $order_mdl->editOrder($update_data);

            //释放座位
            $class_mdl = new ClassModel();
            $class_mdl->releaseSeat($order['class_id'], $order['student_id'], $this->front_shop_id);

            //释放优惠
            $award_where = [
                'student_id' => $order['student_id'],
                'order_id' => $order['id'],
            ];
            $seat = Db::name('award_order')->where($award_where)->find();
            if(count($seat) > 0) {
                Db::name('award_order')->where($award_where)->delete();
            }

            $this->error('该订单已过期','order/FrontOrder/index');
        }

        $out_trade_no = $order['order_id'];//商户订单号
        $total_fee = $order['pay_amount'];//付款金额
        $subject = '学员报班'; //订单名称
        //订单描述
        $body = '学员【'.$order['student_name'].'】报班【'.$order['school_name'].'-'.$order['class_name'].'-'.$order['course_name'].'】';
        //商品展示地址
        $show_url = url(config('alipay_config.success_page'),'',true,true);

        $anti_phishing_key = "";//防钓鱼时间戳(若要使用需调用类文件submit中的query_timestamp函数)
        $exter_invoke_ip = get_client_ip(); //客户端的IP地址

        //读取支付配置参数
        $alipay_config = config('alipay_config');
        $payment_type = "1";//支付类型(必填，不能修改)

        //构造要请求的参数数组
        $parameter = [
            "service" => "create_direct_pay_by_user",
            "partner" => trim($alipay_config['partner']),
            "payment_type" => $payment_type,
            "notify_url"   => $alipay_config['notify_url'],//服务器异步通知页面路径
            "return_url"   => $alipay_config['return_url'],//页面跳转同步通知页面路径
            "seller_email" => $alipay_config['seller_email'],//卖家支付宝帐户
            "out_trade_no" => $out_trade_no,
            "subject"      => $subject,
            "total_fee"    => $total_fee,
            "body"         => $body,
            "show_url"     => $show_url,
            "anti_phishing_key" => $anti_phishing_key,
            "exter_invoke_ip"   => $exter_invoke_ip,
            "_input_charset"    => trim(strtolower($alipay_config['input_charset']))
        ];
        //建立请求
        $alipaySubmit = new \AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter,"post", "确认");
        echo $html_text;
    }

    public function alipay_return()
    {
        //获取支付配置参数
        $config = config('alipay_config');
        $notify = new \AlipayNotify($config);
        //验证支付数据
        $status = $notify->verifyReturn();
        if($status){
            //TODO(steven):下面写验证通过的逻辑,如更改订单状态等
            //验证成功
            $parameter = array(
                "out_trade_no"  => $_GET['out_trade_no'],//商户订单号
                "trade_no"      => $_GET['trade_no'],    //支付宝交易号
                "total_fee"     => $_GET['total_fee'],   //交易金额
                "trade_status"  => $_GET['trade_status'],//交易状态
                "notify_id"     => $_GET['notify_id'],   //通知校验ID
                "notify_time"   => $_GET['notify_time'], //通知的发送时间(格式为yyyy-MM-dd HH:mm:ss)
                "buyer_email"   => $_GET['buyer_email'], //买家支付宝帐号
            );

            if($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
                //进行订单处理，并传送从支付宝返回的参数
                $result = $this->changeOrder($parameter);
                switch ($result){
                    case 1:
                        $msg = '订单号为空';
                        break;
                    case 2:
                        $msg = '没有该订单';
                        break;
                    case 3:
                        $msg = '该订单不是待支付状态';
                        break;
                    case 4:
                        $msg = '修改订单状态失败';
                        break;
                    default:
                        $msg = '成功修改订单状态为已支付';
                        break;
                }
                //以log文件形式记录回调信息
                $log_file = CMF_ROOT."public/alipay.log";//log文件路径
                log_result($log_file, "【支付信息(alipay_return)】".date('Y-m-d H:i:s').":".$msg."\n".print_r($_GET,true)."\n");

                //跳转到配置项中配置的支付成功页面
                $this->redirect(config('alipay_config.success_page'));
            }else{
                echo "trade_status=".$_GET['trade_status'];
                //跳转到配置项中配置的支付失败页面
                $this->redirect(config('alipay_config.error_page'));
            }

            $this->success('支付成功',config('alipay_config.success_page'));
        }else{
            $this->error('支付失败',config('alipay_config.error_page'));
        }
    }

    /**
     *异步接受通知
     */
    public function alipay_notify()
    {
        //获取支付配置参数
        $config = config('alipay_config');
        $alipayNotify = new \AlipayNotify($config);
        //验证支付数据
        $verify_result = $alipayNotify->verifyNotify();
        if($verify_result) {
            //验证成功
            echo "success";//不要修改或删除
            //TODO(steven):下面写验证通过的逻辑,如更改订单状态等
            $parameter = [
                "out_trade_no" => $_POST['out_trade_no'],//商户订单号
                "trade_no"     => $_POST['trade_no'], //支付宝交易号
                "total_fee"    => $_POST['total_fee'],//交易金额
                "trade_status" => $_POST['trade_status'],//交易状态
                "notify_id"    => $_POST['notify_id'], //通知校验ID
                "notify_time"  => $_POST['notify_time'], //通知的发送时间(格式为yyyy-MM-dd HH:mm:ss)
                "buyer_email"  => $_POST['buyer_email'], //买家支付宝帐号
            ];
            if($_POST['trade_status'] == 'TRADE_FINISHED') {
                //
            }elseif ($_POST['trade_status'] == 'TRADE_SUCCESS') {
                //进行订单处理，并传送从支付宝返回的参数
                $result = $this->changeOrder($parameter);
                switch ($result){
                    case 1:
                        $msg = '订单号为空';
                        break;
                    case 2:
                        $msg = '没有该订单';
                        break;
                    case 3:
                        $msg = '该订单不是待支付状态';
                        break;
                    case 4:
                        $msg = '修改订单状态失败';
                        break;
                    default:
                        $msg = '成功修改订单状态为已支付';
                        break;
                }
                //以log文件形式记录回调信息
                $log_file = CMF_ROOT."public/alipay.log";//log文件路径
                log_result($log_file, "【支付信息(alipay_notify)】".date('Y-m-d H:i:s').":".$msg."\n".print_r($_POST,true)."\n");
            }

        }else {
            echo "fail";
        }
    }

    /**
     * 支付成功后修改订单
     * @param array $parameter
     * @return bool
     */
    public function changeOrder($parameter)
    {
        if(empty($parameter['out_trade_no'])){
            return 1;
        }
        $order_id = $parameter['out_trade_no'];
        $cur_date = time();

        $where = [
            'o.order_id' => ['=', $order_id],
        ];
        //根据订单号获取订单信息
        $order_mdl = new OrderModel();
        $data = $order_mdl->getOrderByField($where);
        if(count($data) <= 0){
            //没有订单
            return 2;
        }
        if($data['order_status'] != 0){
            //非待支付
            return 3;
        }

        $update_data = [
            'id' => $data['id'],
            'order_status' => 1,//已支付
            'payment' => 1,//支付方式(1:支付宝)
            'pay_no' => $parameter['trade_no'],//支付流水号
            'pay_time' => $cur_date,//支付时间
            'update_time' => $cur_date,
        ];
        //修改订单
        $result = $order_mdl->editOrder($update_data);
        if(!$result){
            //修改失败
            return 4;
        }

        //记录日志
        $pk = $data['id']; //主键
        $table = 'order';//数据表名
        $content = lang('CHANGE_PAY_ORDER_STATUS', ['orderId' => $order_id]);
        do_log($content, $pk, $table, $cur_date);

        return 5;
    }


}